package com.example.project.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.project.common.properties.WeChatProperties;
import com.example.project.common.utils.HttpClientUtil;
import com.example.project.mapper.UserMapper;
import com.example.project.pojo.entity.User;
import com.example.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    //微信服务地址
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;

    private UserMapper userMapper;
    /**
     * 微信登录
     * @param code
     * @return
     */
    public User wxLogin(String code) {

        //调用微信接口服务获得当前微信用户openid
        String openid=getOpenid(code);

        //判断是否获取到openid（为空）
        if(openid==null){
            throw null ;
        }
        //判断是否为新用户
        User user=userMapper.getByOpenId(openid);
        //是新用户完成注册
        if(user==null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }

    //通过code请求微信服务器获取openid
    private  String getOpenid(String code){
        //调用微信接口服务，获取openId
        Map<String,String>map=new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json=HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject= JSON.parseObject(json);
        String openid=jsonObject.getString("openid");
        return openid;
    }
}
